package com.zte.shopping.action.backend;

import com.zte.shopping.constant.ResponseCodeConstant;
import com.zte.shopping.entity.Dept;
import com.zte.shopping.entity.Staff;
import com.zte.shopping.entity.User;
import com.zte.shopping.exception.LoginDisabledException;
import com.zte.shopping.exception.NoPromissionException;
import com.zte.shopping.exception.RequestParameterException;
import com.zte.shopping.exception.StaffExistException;
import com.zte.shopping.service.DeptService;
import com.zte.shopping.service.StaffService;
import com.zte.shopping.util.PageSupport;
import com.zte.shopping.util.ResponseResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @program: ssm
 * @description: 后台员工管理界面
 * @author: zuti
 * @create: 2020-06-23 22:10
 **/
@Controller
@RequestMapping("staff")
public class BackendStaffManagerController {

    private  static  final Logger logger= Logger.getLogger(BackendStaffManagerController.class);
    @Autowired
    StaffService staffService;
    @Autowired
    DeptService deptService;

    @RequestMapping("/toStaff")
    public String  toStaffManager(@RequestParam(value = "pageIndex",required = false,defaultValue = "1")Integer pageIndex,
                                 Model model){
        logger.debug("enterBackendStaffManagerController------> toStaffManager param: pageIndex"+pageIndex);
        List<Staff> staffList = staffService.staffList(pageIndex);
        logger.debug("enter BackendStaffManagerController------> toStaffManager UserList : size" + staffList.size());
        for(int i=0;i<staffList.size();i++) {
            Staff staff = staffList.get(i);
            logger.debug("StaffId="+staff.getStaffId()+" LoginName="+staff.getLoginName()+" phone="+staff.getPhone()
                    );
        }
        PageSupport pageSupport = new PageSupport();
        pageSupport.setTotalCount(this.staffService.staffListCount());
        pageSupport.setCurrentPageNo(pageIndex);

        //查询部门列表
        List<Dept> deptList  = deptService.deptList(1);
        model.addAttribute("deptList",deptList);

        model.addAttribute("pageSupport", pageSupport);
        model.addAttribute("StaffList", staffList);


        return "backend/staffManager";
    }

    @RequestMapping(value = "/searchByParamList")
    public String  UserManagerSearch(@RequestParam(value = "pageIndex",required = false,defaultValue = "1")Integer pageIndex,
                                     @RequestParam(value = "searchUserName",required = false)  String UserName,
                                     @RequestParam(value = "searchLoginName",required = false)  String LoginName,
                                     @RequestParam(value = "searchPhone",required = false)  String Phone,
                                     @RequestParam(value = "searchEmail",required = false)  String Email,
                                     @RequestParam(value = "searchDeptId",required = false)  Integer DeptId,
                                     @RequestParam(value = "searchIsValid",required = false,defaultValue = "-1")  Integer IsValid,
                                     Model model) {

        logger.debug("enter UserManagerSearch------> UserManagerSearch param: pageIndex=" + pageIndex + "searchName=" + UserName +
                " searchLoginName=" + LoginName + " searchPhone=" + Phone + "searchEmail=" + Email +" searchDeptId="+DeptId+ " searchIsValid" + IsValid);
        if (IsValid == -1) {
            IsValid = null;
        }
        List<Staff> staffList = staffService.searchStaffByParmaList(pageIndex, UserName, LoginName, Phone, Email,DeptId, IsValid);


        logger.debug("enter UserManagerSearch------> toUserManager UserList : size" + staffList.size());
        for (int i = 0; i < staffList.size(); i++) {
            Staff staff = staffList.get(i);
            logger.debug("staffId=" + staff.getStaffId() + " LoginName=" + staff.getLoginName() + " email=" + staff.getEmail() + " phone=" + staff.getPhone()
                    );
        }

        PageSupport pageSupport = new PageSupport();
        pageSupport.setTotalCount(this.staffService.staffListCountByParamList( UserName, LoginName, Phone, Email,DeptId, IsValid));
        pageSupport.setCurrentPageNo(pageIndex);

        //查询部门列表
        List<Dept> deptList  = deptService.deptList(1);
        model.addAttribute("deptList",deptList);

        model.addAttribute("pageSupport", pageSupport);
        model.addAttribute("StaffList", staffList);



        return "backend/staffManager";
    }

    /**
     * @Author zuti
     * @Description //TODO 修改状态
     * @Date 9:01 2020/6/29
     * @Param
     * @return
     **/
    @ResponseBody
    @RequestMapping("/modifyStaffStatus")
    public ResponseResult modifyStatus(@RequestParam("staffId") String staffId,
                                       @RequestParam("isValid") String isValid)
    {
        ResponseResult result = new ResponseResult();

        try
        {
            staffService.modifyStaffStatus(staffId, isValid);

            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);

        } catch (Exception e)
        {
            e.printStackTrace();

            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        logger.debug("enter StaffManagerController------> tomodifyStatus param : stafffId=" + staffId+" isValid="+isValid
        +"===========result: result.Message="+result.getMessage()+" result.ResponseCode="+result.getResponseCode());

        return result;
    }

    /**
     * 添加管理员
     *
     *
     * 默认田间的员工为有效状态
     *"staffName":$("#addStaffName").val(),
     *                         "loginName":$("#addLoginName").val(),
     *                         "password":$("#addPassword").val(),
     *                         "phone":$("#addPhone").val(),
     *                         "email":$("#addEmail").val(),
     *                         "deptId":$("#addDept")[0].options[$("#addDept")[0].selectedIndex].value,
     *                         "role":$("#addRole")[0].value
     */
    @ResponseBody
    @RequestMapping("/addStaff")
    public ResponseResult addStaff(@RequestParam("loginName") String loginName,
                                    @RequestParam("password")String password,
                                    @RequestParam("phone")String phone,
                                    @RequestParam("email") String email,
                                    @RequestParam("deptId") String deptId,
                                    @RequestParam("role") String role,
                                   HttpSession session)
    {
        ResponseResult result = new ResponseResult();
        Staff staff=new Staff();
        staff.setLoginName(loginName);
        staff.setPassword(password);
        staff.setPhone(phone);
        staff.setEmail(email);
        staff.setRole(role);
        try
        {
            staffService.addStaff(staff, deptId, session);

            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);

        } catch (LoginDisabledException e)
        {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_LOGIN_TIMEOUT);

        } catch (NoPromissionException e)
        {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_NO_PROMISSON);
        } catch(Exception e)
        {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        logger.debug("enter StaffManagerController------> addStaff param staff: stafffId=" + staff.getStaffId()+" staffName="+staff.getStaffName()+
                " deptId="+deptId
                +"===========result: result.Message="+result.getMessage()+" result.ResponseCode="+result.getResponseCode());
        return result;
    }

    /**
     * 做修改管理员操作时  查询出修改页面的管理员信息
     *
     * 根据id查询员工信息
     */
    @ResponseBody
    @RequestMapping(value = "/findById",method = RequestMethod.POST)
    public ResponseResult findById(@RequestParam(value = "staffId",required = false,defaultValue = "1") String staffId,
                                   @RequestParam("isValid")Integer isValid)
    {
        logger.debug("BackendStaffManagerController=======>findById staffId="+staffId+"isValid="+isValid);
        ResponseResult result = new ResponseResult();
        Staff staff = staffService.findById(staffId);

        result.setMessage("成功");
        result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);
        result.setReturnObject(staff);


        logger.debug("enter StaffManagerController------> findById param staff: staffId=" + staffId

                +"===========result: result.Message="+result.getMessage()+" result.ResponseCode="+result.getResponseCode());

        return result;
    }


    /**
     * 修改员工管理员
     * "staffId"   :  $("#modifyStaffId").val(),
     *                         "staffName" :  $("#modifyStaffName").val(),
     *                         "phone"     :  $("#modifyPhone").val(),
     *                         "email"     :  $("#modifyEmail").val(),
     *                         "role"      :  $("#modifyRole").val(),
     *                         "deptId"    :  $("#modifyDept").val()
     */
    @ResponseBody
    @RequestMapping("/modifyStaff")
    public ResponseResult modifyStaff(@RequestParam(value = "staffId",required = true) Integer staffId,
                                      @RequestParam(value = "staffName",required = false) String staffName,
                                      @RequestParam(value = "phone",required = false)String phone,
                                      @RequestParam(value = "email",required = false) String email,
                                      @RequestParam(value = "role",required = false) String role,
                                      @RequestParam(value = "deptId",required = false) String deptId
                                     )
    {
        ResponseResult result = new ResponseResult();
        Staff staff = new Staff();
        staff.setStaffId(staffId);
        staff.setStaffName(staffName);
        staff.setPhone(phone);
        staff.setEmail(email);
        staff.setRole(role);
        try
        {
            staffService.modifyStaff(staff, deptId);

            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);

        } catch(RequestParameterException e)
        {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_REQUEST_PARAMETER_ERROR);

        } catch (Exception e)
        {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }
        logger.debug("enter StaffManagerController------> addStaff param staff: stafffId=" + staff.getStaffId()+" staffName="+staff.getStaffName()+
                " deptId="+deptId
                +"===========result: result.Message="+result.getMessage()+" result.ResponseCode="+result.getResponseCode());
        return result;
    }




}
